<template>
	<view class="container">
		<uni-popup ref="specPopup" type="bottom" :safe-area="false" :mask-click="true">
			<view class="spec-modal">
				<!-- Header with close button -->
				<view class="modal-header">
					<view class="close-btn" @click="close">×</view>
				</view>

				<scroll-view scroll-y class="modal-content">
					<!-- Address Selection -->
					<view class="address-section" @click="selectAddress">
						<view class="address-icon">
							<text class="location-icon">📍</text>
						</view>
						<view class="address-info">
							<view v-if="selectedAddress" class="address-detail">
								{{selectedAddress.province}}{{selectedAddress.city}}{{selectedAddress.district}}{{ selectedAddress.detail }}
							</view>
							<view v-if="selectedAddress" class="contact-info">
								{{ selectedAddress.realName }} {{ selectedAddress.phone }}
							</view>
							<view v-else class="add-address-text">点击添加收货地址</view>
						</view>
						<view class="address-arrow">
							<text>›</text>
						</view>
					</view>

					<!-- 积分余额显示 -->
					<view class="integral-section">
						<view class="integral-icon">
							<image src="https://cos.ruilongan.com/XCX/2025/08/29/积分log@2x_20250829135415A003.png"
								mode="aspectFit" style="width: 32rpx; height: 32rpx;" @error="onImageError">
							</image>
						</view>
						<view class="integral-info">
							<view class="integral-details">
								<view class="integral-label">可用积分</view>
								<view class="integral-amount">{{ usableIntegral }}</view>
							</view>
							<view class="integral-details" v-if="!isIntegralSufficient">
								<view class="integral-warning">积分不足</view>
							</view>
							<view class="integral-details" v-else>
								<view class="integral-remaining">剩余: {{ remainingIntegral }}</view>
							</view>
						</view>
					</view>

					<!-- Product info, color and size selection -->
					<view class="product-container">
						<view class="product-info">
							<view class="image-container" @click="previewImage(selectedSpec.picUrl)">
								<image :src="selectedSpec.picUrl | avatarUrlFind('1')" mode="aspectFill"
									class="product-image"></image>
							</view>
							<view class="info-right">
								<view class="price">
									<text class="current-price">
										<image
											src="https://cos.ruilongan.com/XCX/2025/08/29/积分log@2x_20250829135415A003.png"
											mode="aspectFit"
											style="width: 32rpx; height: 32rpx; vertical-align: middle; margin-right: 8rpx;"
											@error="onImageError"></image>
										{{ currentPrice.salesPrice }}
									</text>
								</view>
								<view class="price">
									<text class="yuan">市场价：</text>
									<text class="original-price">¥{{ currentPrice.dashingPrice }}</text>
								</view>
								<view class="selected-info">
									<view class="quantity-selector">
										<view class="quantity-btn" @click="decreaseQuantity">-</view>
										<input type="number" v-model="quantity" class="quantity-input" />
										<view class="quantity-btn" @click="increaseQuantity">+</view>
									</view>
								</view>
							</view>
						</view>

						<!-- Specification selection -->
						<view class="spec-section" v-if="product.goodsCategory==='P'||product.goodsCategory==='JP'">
							<view class="section-title">规格 ({{ product.speciList ? product.speciList.length : 0 }})
							</view>
							<view class="spec-options">
								<view v-for="(item, index) in product.speciList" :key="index" class="spec-option"
									:class="{ active: selectedSpec && selectedSpec.skuCode === item.skuCode }"
									@click="selectColor(item)">
									{{ item.speciName || '未知规格' }}
								</view>
							</view>
						</view>

						<view class="spec-section" v-if="product.goodsCategory==='TC'">
							<view class="section-title">包含商品 ({{ product.speciList ? product.speciList.length : 0 }})
							</view>
							<view class="spec-options">
								<view v-for="(item, index) in product.speciList" :key="index" class="spec-item">
									{{ item.speciName || '未知规格' }}x{{item.participationNum}}
								</view>
							</view>
						</view>
					</view>





				</scroll-view>

				<!-- Fixed bottom area -->
				<view class="fixed-bottom">
					<view class="confirm-btn" :class="{ 'disabled': !isIntegralSufficient }" @click="confirmSelection">
						立即兑换
						<text class="price-amount">
							<image src="https://cos.ruilongan.com/XCX/2025/08/29/积分log@2x_20250829135415A003.png"
								mode="aspectFit"
								style="width: 24rpx; height: 24rpx; vertical-align: middle; margin: 0 8rpx;"
								@error="onImageError"></image>
							{{ totalPrice.salesPrice }}
						</text>
					</view>
				</view>
			</view>
		</uni-popup>




	</view>
</template>

<script>
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth'

	import {
		listAddress
	} from '@/api/userAddress.js'
	import {
		getUserInfo
	} from '@/api/vipUser.js'
	import {
		createOrder
	} from '@/api/order.js'


	export default {
		name: 'SpecificationModal',
		props: {
			product: {
				type: Object,
				required: true,
				default: () => ({})
			},
			salesPrice: {
				type: [String, Number],
				required: false,
				default: '0'
			},
			dashingPrice: {
				type: [String, Number],
				required: false,
				default: '0'
			}
		},
		data() {
			return {
				selectedSpec: {},
				quantity: 1,
				selectedAddress: null, // 选中的地址信息
				addressList: [], // 地址列表
				usableIntegral: 0,
			}
		},
		watch: {
			product: {
				immediate: true,
				handler(newVal) {
					// 当商品数据更新时，默认选中第一个规格
					if (newVal && newVal.speciList && newVal.speciList.length > 0) {
						this.selectColor(newVal.speciList[0])
						this.selectedSpec = newVal.speciList[0]
						console.log(this.selectedSpec)
					} else {
						this.selectedSpec = {}
					}
				}
			}
		},
		mounted() {
			// 加载地址列表
			this.loadAddressList();
			this.getUserInfo();

			// 监听地址选择事件
			uni.$on('addressSelected', this.handleAddressSelected);
		},
		beforeDestroy() {
			// 移除事件监听
			uni.$off('addressSelected', this.handleAddressSelected);
		},
		computed: {
			// 当前选中规格的价格
			currentPrice() {
				if (this.selectedSpec) {
					return {
						salesPrice: this.selectedSpec.salesPrice,
						dashingPrice: this.selectedSpec.dashingPrice
					}
				}
				return {
					salesPrice: this.salesPrice,
					dashingPrice: this.dashingPrice
				}
			},
			// 计算总价格（实付价格 × 数量）
			totalPrice() {
				const salesPrice = Number(this.currentPrice.salesPrice) || 0
				const dashingPrice = Number(this.currentPrice.dashingPrice) || 0
				const quantity = Number(this.quantity) || 1

				// 格式化价格，如果是整数则不显示小数
				const formatPrice = (price) => {
					const total = price * quantity
					return total % 1 === 0 ? total.toString() : total.toFixed(2)
				}

				return {
					salesPrice: formatPrice(salesPrice),
					dashingPrice: formatPrice(dashingPrice)
				}
			},
			// 检查积分是否足够
			isIntegralSufficient() {
				const requiredIntegral = Number(this.totalPrice.salesPrice)
				const availableIntegral = Number(this.usableIntegral)
				return availableIntegral >= requiredIntegral
			},
			// 计算兑换后剩余积分
			remainingIntegral() {
				const requiredIntegral = Number(this.totalPrice.salesPrice)
				const availableIntegral = Number(this.usableIntegral)
				return Math.max(0, availableIntegral - requiredIntegral)
			}
		},
		methods: {

			getUserInfo() {
				const userId = this.$store.state.user.userId
				if (getToken()){
					getUserInfo(userId).then(res => {
						if (res.code === 200 && res.data) {
							this.usableIntegral = res.data.usableIntegral || 0
						}
					}).catch(error => {
						console.error('获取用户信息失败:', error)
						uni.showToast({
							title: '获取用户信息失败',
							icon: 'none'
						})
					})
				}
			},

			onImageError(e) {
				console.log('图片加载失败:', e)
				// 可以设置一个默认图片或者隐藏图片
			},
			previewImage(picUrl) {
				picUrl = config.remotePicUrlPd + picUrl
				console.log('点击预览图片，当前规格:', picUrl)

				// 只预览当前选中规格的图片
				if (picUrl) {
					uni.previewImage({
						current: picUrl, // 当前显示图片的链接
						urls: [picUrl], // 只包含当前规格的图片
						success: () => {
							console.log('图片预览成功')
						},
						fail: (err) => {
							console.error('图片预览失败:', err)
							uni.showToast({
								title: '图片预览失败',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '暂无图片可预览',
						icon: 'none'
					})
				}
			},
			open() {
				this.$refs.specPopup.open()
				// 每次打开弹窗时重新获取用户信息，确保积分余额是最新的
				this.getUserInfo()
			},
			close() {
				this.$refs.specPopup.close()
			},
			selectAddress() {
				// 跳转到地址选择页面
				uni.navigateTo({
					url: '/subPackage_1/pages/mine/address/address-list?selectMode=true'
				})
			},
			// 选择规格
			selectColor(spec) {
				console.log('选择规格:', spec)
				if (this.product.goodsCategory === 'TC') {

				} else {
					this.selectedSpec = spec
					// 触发事件通知父组件价格变化
					this.$emit('spec-change', {
						salesPrice: spec.salesPrice,
						dashingPrice: spec.dashingPrice,
						spec: spec
					})
				}
			},
			selectSize(size) {
				this.selectedSize = size
			},
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--
				}
			},
			increaseQuantity() {
				this.quantity++
			},

			confirmSelection() {
				
				// 检查是否选择了地址
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请先选择收货地址',
						icon: 'none'
					})
					return
				}

				// 检查是否选择了规格
				if (!this.selectedSpec || !this.selectedSpec.skuCode) {
					uni.showToast({
						title: '请选择商品规格',
						icon: 'none'
					})
					return
				}

				// 检查积分余额是否足够
				const requiredIntegral = Number(this.totalPrice.salesPrice)
				const availableIntegral = Number(this.usableIntegral)

				if (availableIntegral < requiredIntegral) {
					uni.showModal({
						title: '积分不足',
						content: `您的可用积分为 ${this.usableIntegral}，需要 ${this.totalPrice.salesPrice} 积分，积分余额不足，无法完成兑换。`,
						showCancel: false,
						confirmText: '我知道了'
					})
					return
				}

				//拼装订单数据
				let mallOrder = {}
				mallOrder.userId = this.$store.state.user.userId
				mallOrder.orderType = '1'
				mallOrder.totalNum = this.quantity
				mallOrder.totalAmount = this.totalPrice.salesPrice
				mallOrder.discountAmount = 0
				mallOrder.payableAmount = this.totalPrice.salesPrice
				mallOrder.goodsCategory = this.product.goodsCategory
				mallOrder.drugCode = this.product.drugCode
				mallOrder.drugId = this.product.id

				//TODO 地址相关信息
				let orderAddress = {}
				orderAddress.receiveUserName = this.selectedAddress ? this.selectedAddress.realName :
					''
				orderAddress.receiveUserPhone = this.selectedAddress ? this.selectedAddress.phone : ''
				orderAddress.receiveUserAddress = this.selectedAddress ? this.selectedAddress.detail :
					''
				orderAddress.receiveProvince = this.selectedAddress ? this.selectedAddress.province : ''
				orderAddress.receiveCity = this.selectedAddress ? this.selectedAddress.city : ''
				orderAddress.receiveCounty = this.selectedAddress ? this.selectedAddress.district : ''
				mallOrder.orderAddress = orderAddress

				mallOrder.onlinePayMode = 'points'

				let orderDetailList = []
				if (this.product.goodsCategory !== 'TC') {
					this.selectedSpec.price = this.currentPrice.salesPrice
					this.selectedSpec.num = this.quantity
					this.selectedSpec.amount = this.totalPrice.salesPrice
					orderDetailList.push(this.selectedSpec)
					mallOrder.orderDetailList = orderDetailList
				}

				// 支持多种支付方式
				let orderPayList = []
				let balancePayDetail = {}
				balancePayDetail.payMode = 'points' // 储值余额支付
				balancePayDetail.paymentAmount = this.currentPrice.salesPrice
				orderPayList.push(balancePayDetail)


				mallOrder.orderPayList = orderPayList

				mallOrder.isPoints = '1'


				console.log(mallOrder)

				uni.showLoading({
					title: '正在提交订单...'
				})
				createOrder(mallOrder).then(res => {
					if (res.code === 200 && res.data) {
						uni.hideLoading();
						uni.showToast({
							title: '支付成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/subPackage_1/pages/order/order-list?tab_cur=0'
							});
						}, 1500);
					}
				}).catch(error => {
					uni.hideLoading()
					uni.showToast({
						title: error.message || '创建订单失败',
						icon: 'none'
					})
				})

			},


			async loadAddressList() {
				try {
					if (getToken()) {
						listAddress({
							userId: this.$store.state.user.userId
						}).then(res => {
							if (res.code === 200) {
								this.addressList = res.rows;
								// 优先选择标记为默认的地址，如果没有则选择第一个地址
								if (this.addressList.length > 0) {
									// 查找默认地址
									const defaultAddr = this.addressList.find(item => item.isDefault === '1');
									if (defaultAddr) {
										this.selectedAddress = defaultAddr;
										console.log('使用默认地址:', this.selectedAddress);
									} else {
										// 如果没有默认地址，使用第一个地址
										this.selectedAddress = this.addressList[0];
										console.log('使用第一个地址作为默认地址:', this.selectedAddress);
									}
								}
							} else {
								uni.showToast({
									title: res.msg || '获取地址列表失败',
									icon: 'none'
								});
							}
						})
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取地址列表失败',
						icon: 'none'
					});
				}
			},
			// 处理地址选择
			handleAddressSelected(address) {
				this.selectedAddress = address;
				uni.showToast({
					title: '地址选择成功',
					icon: 'success'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.spec-modal {
		background-color: #f6f6f6;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		position: relative;
		height: 72vh;
		display: flex;
		flex-direction: column;
		overflow: hidden; // 防止内容溢出
	}

	.modal-header {
		background-color: #f6f6f6;
		text-align: right;
		// padding: 10rpx 10rpx;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		flex-shrink: 0;
		padding-right: 10rpx;
	}

	.close-btn {
		font-size: 60rpx;
		color: #999;
		padding: 10rpx;
	}

	.modal-content {
		flex: 1;
		background-color: #f6f6f6;
		padding: 0 20rpx;
		height: 0;
		position: relative;
		overflow-y: auto;
		margin-bottom: 80px;
	}

	// 移除之前的底部间距占位
	scroll-view {
		height: 100%;
	}

	.address-section {
		display: flex;
		align-items: center;
		padding: 20rpx 26rpx;
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 10px;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.address-icon {
			font-size: 40rpx;
			margin-right: 20rpx;
		}

		.address-info {
			flex: 1;

			.address-detail {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 10rpx;
			}

			.contact-info {
				font-size: 24rpx;
				color: #666;
			}

			.add-address-text {
				font-size: 28rpx;
				color: #666;
				text-align: center;
				padding: 20rpx 0;
			}
		}

		.address-arrow {
			color: #999;
			font-size: 32rpx;
		}
	}

	.integral-section {
		display: flex;
		align-items: center;
		padding: 20rpx 26rpx;
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 10px;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.integral-icon {
			margin-right: 20rpx;
		}

		.integral-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			gap: 10rpx;

			.integral-details {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.integral-label {
					font-size: 28rpx;
					color: #333;
				}

				.integral-amount {
					font-size: 32rpx;
					color: #F54414;
					font-weight: bold;
				}

				.integral-warning {
					font-size: 24rpx;
					color: #ff4757;
					font-weight: bold;
				}

				.integral-remaining {
					font-size: 24rpx;
					color: #2ed573;
				}
			}
		}
	}

	.product-info {
		display: flex;
		margin-bottom: 30rpx;
		padding: 20rpx;
		position: relative;

		.image-container {
			position: relative;
			cursor: pointer;
			transition: all 0.3s ease;

			&:active {
				.product-image {
					transform: perspective(800rpx) rotateX(2deg) scale(0.98);
				}
			}
		}

		.product-image {
			width: 240rpx;
			height: 240rpx;
			border-radius: 18rpx;
			box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1),
				0 16rpx 28rpx rgba(0, 0, 0, 0.08),
				0 2rpx 4rpx rgba(255, 255, 255, 0.1) inset;
			position: relative;
			top: -70rpx;
			margin-bottom: -60rpx;
			// border: 1rpx solid rgba(255, 255, 255, 0.2);
			transform: perspective(800rpx) rotateX(2deg);
			transition: all 0.3s ease;
		}

		.preview-overlay {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			width: 60rpx;
			height: 60rpx;
			background: rgba(0, 0, 0, 0.6);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			opacity: 1;
			z-index: 2;

			.preview-icon {
				font-size: 32rpx;
				color: #fff;
			}
		}

		.info-right {
			flex: 1;
			margin-left: 46rpx;

			.price {
				margin-bottom: 10rpx;

				.current-price {
					color: #F54414;
					font-size: 48rpx;
					margin-right: 10rpx;
				}

				.original-price {
					color: #999;
					text-decoration: line-through;
					font-size: 32rpx;
				}

				.yuan {
					color: #999;
					font-size: 32rpx;
				}
			}

			.selected-info {
				display: flex;
				align-items: center;
				color: #666;
				font-size: 28rpx;
				margin-top: 20rpx;

				.quantity-selector {
					display: flex;
					align-items: center;

					.quantity-btn {
						width: 50rpx;
						height: 50rpx;
						border: 2rpx solid #ddd;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 32rpx;
						color: #333;
						background: #fff;
					}

					.quantity-input {
						width: 80rpx;
						height: 50rpx;
						text-align: center;
						border-top: 2rpx solid #ddd;
						border-bottom: 2rpx solid #ddd;
						margin: 0;
						font-size: 28rpx;
					}
				}
			}
		}
	}

	.product-container {
		background: #fff;
		border-radius: 10px;
		padding: 20rpx 10rpx;
		margin-bottom: 30rpx;
		margin-top: 60rpx;
	}

	.spec-section {
		margin-bottom: 30rpx;
		padding: 0 20rpx;

		.section-title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;
		}

		.spec-options {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.spec-option {
				min-width: 120rpx;
				text-align: center;
				padding: 15rpx 30rpx;
				border: 2rpx solid #ddd;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #333;

				&.active {
					border-color: #FAAC1B;
					color: #FAAC1B;
				}
			}

			.spec-item {
				min-width: 120rpx;
				text-align: center;
				padding: 15rpx 30rpx;
				background: #f8f8f8;
				border-radius: 8rpx;
				font-size: 28rpx;
				color: #666;
				border: none;
			}
		}
	}

	.quantity-section {
		margin-bottom: 30rpx;

		.quantity-selector {
			display: flex;
			align-items: center;

			.quantity-btn {
				width: 60rpx;
				height: 60rpx;
				border: 2rpx solid #ddd;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 32rpx;
			}

			.quantity-input {
				width: 80rpx;
				height: 60rpx;
				text-align: center;
				border-top: 2rpx solid #ddd;
				border-bottom: 2rpx solid #ddd;
			}
		}
	}





	.agreement-section {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-top: 1rpx solid #f5f5f5;

		.custom-checkbox {
			width: 32rpx;
			height: 32rpx;
			border-radius: 50%;
			border: 2rpx solid #ddd;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.2s;

			&.checked {
				background-color: #09ab4f;
				border-color: #09ab4f;
			}

			.checkbox-inner {
				color: #fff;
				font-size: 20rpx;
				line-height: 1;
				transform: translateY(-1rpx);
			}
		}

		.agreement-text {
			font-size: 20rpx;
			color: #666;
			margin-left: 10rpx;

			.link {
				color: #09ab4f;
			}
		}
	}

	.confirm-btn {
		background: linear-gradient(135deg, #FAAC1B 0%, #F7931E 100%);
		color: #fff;
		text-align: center;
		font-size: 32rpx;
		padding: 30rpx;
		border-radius: 10rpx;
		transition: all 0.3s;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		cursor: pointer;

		&:active {
			transform: scale(0.98);
		}

		&.disabled {
			background: linear-gradient(135deg, #ccc 0%, #999 100%);
			cursor: not-allowed;
			opacity: 0.6;

			&:active {
				transform: none;
			}
		}

		.price-amount {
			display: flex;
			align-items: center;
			font-size: 36rpx;
			opacity: 0.9;
		}
	}

	.fixed-bottom {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 1;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 20rpx;
	}
</style>